import { defineStore } from 'pinia'
import { ref, watch, computed } from 'vue'
import { usePageDialogStore } from '@/stores/pageDialog'
import { HtmlModulesPath, HtmlModulesMenuFileName } from '@/utils/constants'
import { useConnectionStore } from '@/stores/connection'
import { agencyAsync } from '@/appox/appox'
import { appoxEnums } from '@/appox/appox'
import { biBridge } from '@/appox/bi-bridge'

export const useHtmlModuleStore = defineStore('htmlModule', () => {
  // 状态
  const entryName = ref(localStorage.getItem('AppoxJsTest.HtmlEntryName') || 'my_page')
  const viewConfig = ref('')
  const htmlModules = ref([])
  const canOpenDialog = ref(false)
  const showHelpForHtmlModules = ref(false)
  const embedderEntryName = ref('')
  const embedderBridgeId = ref('')
  const showDevelPanel = ref(false)

  // 从menu.xml读取HTML模块列表
  async function loadHtmlModules() {
    try {
      const response = await fetch(`${HtmlModulesPath}/${HtmlModulesMenuFileName}`)
      const xmlText = await response.text()
      const parser = new DOMParser()
      const xmlDoc = parser.parseFromString(xmlText, "text/xml")
      htmlModules.value = Array.from(xmlDoc.getElementsByTagName("html_module"))
        .map(module => module.textContent)
    } catch (error) {
      console.error('Error loading menu.xml:', error)
      htmlModules.value = []
    }
  }

  // 加载HTML模块配置
  function loadHtmlModuleConfig() {
    const savedEntryName = localStorage.getItem('AppoxJsTest.HtmlEntryName')
    if (savedEntryName) entryName.value = savedEntryName
  }

  // 保存HTML模块配置
  function saveHtmlModuleConfig() {
    if (entryName.value) localStorage.setItem('AppoxJsTest.HtmlEntryName', entryName.value)
  }

  // 打开对话框相关
  async function updateAppStatus() {
    let appStatus = await agencyAsync.getAppStatus();
    canOpenDialog.value = appStatus === appoxEnums.ApplicationStatus.Idle
  }

  async function openDialog() {
    saveHtmlModuleConfig()
    unloadDevelPanel()
    const pageDialogStore = usePageDialogStore()
    await pageDialogStore.show(entryName.value, viewConfig.value, showHelpForHtmlModules.value)
    loadDevelPanel()
  }

  // 监听状态变化并保存到localStorage
  watch(entryName, (newValue) => {
    if (newValue) {
      localStorage.setItem('AppoxJsTest.HtmlEntryName', newValue)
      loadDevelPanel()
    }
  })

  async function loadDevelPanel() {
    unloadDevelPanel()

    if (useConnectionStore().isConnected && await agencyAsync.getAppStatus() != appoxEnums.ApplicationStatus.Idle) return

    const htmlModuleInstInfo = await biBridge.initializeModule(HtmlModulesPath, entryName.value, viewConfig.value, showHelpForHtmlModules.value)
    embedderEntryName.value = entryName.value
    embedderBridgeId.value = htmlModuleInstInfo.bridgeId
    showDevelPanel.value = true
  }

  function unloadDevelPanel() {
    biBridge.releaseModule(embedderBridgeId.value)
    embedderEntryName.value = ''
    embedderBridgeId.value = ''
    showDevelPanel.value = false
  }

  return {
    // 状态
    entryName,
    viewConfig,
    htmlModules,
    canOpenDialog,
    showHelpForHtmlModules,
    embedderEntryName,
    embedderBridgeId,
    showDevelPanel,
    // 动作
    loadHtmlModuleConfig,
    saveHtmlModuleConfig,
    openDialog,
    loadDevelPanel,
    unloadDevelPanel,
    loadHtmlModules,
    updateAppStatus,
  }
})